package com.whmnx.fishfamily;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.huanwei.cc.CheliangGuiJi;
import com.huanwei.cc.R;
import com.huanwei.cc.utils.AMapUtil;
import com.huanwei.cc.utils.DrivingRouteOverlay;
import com.huanwei.cc.utils.JSONUtils;
import com.huanwei.http.API;
import com.huanwei.http.Okhttp;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class MyMapActivity extends BaseActivity2 implements AMap.OnMapLoadedListener, RouteSearch.OnRouteSearchListener {
    @BindView(R.id.map)
    MapView mMapView;
    private AMap aMap;

    private RouteSearch mRouteSearch;
    private final int ROUTE_TYPE_DRIVE = 2;

    private LatLonPoint mStartPoint;//起点，39.942295,116.335891
    private LatLonPoint mEndPoint;//终点，39.995576,116.481288
    private DriveRouteResult mDriveRouteResult;
    String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        ButterKnife.bind(this);
        mMapView.onCreate(savedInstanceState);
        name = getIntent().getStringExtra("name");
        initMap();
        getCoor();
    }

    KProgressHUD dialog;
    List<CheliangGuiJi.DataBean> data;

    public void showdialog() {
        dialog = KProgressHUD.create(MyMapActivity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在加载数据，请稍候")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
    }

    private void getCoor() {
        API.VehicleTrack(name, new Okhttp.Objectcallback() {
            @Override
            public void onsuccess(String st) {
                Log.e("zzzz", "获取轨迹" + st);
                if (dialog != null) {
                    dialog.dismiss();
                }
                CheliangGuiJi cheliangGuiJi = JSONUtils.parseJSON(st, CheliangGuiJi.class);
                if (cheliangGuiJi.getCode() == 10001) {
                    data = cheliangGuiJi.getData();
                    setfromandtoMarker(data);
                }

            }

            @Override
            public void onFalia(int code, String errst) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                Log.e("zzzz", "获取轨迹错误" + errst);
                Toast.makeText(MyMapActivity.this, "获取轨迹网络错误", Toast.LENGTH_SHORT).show();
            }
        });

//        Map<String, String> map = new HashMap<>();
//        map.put("userId", user.getId());
//        OkGo.<BaseResponse<ArrayList<Coor>>>post(Config.API.getCoor).params(map).execute(new JsonCallback<BaseResponse<ArrayList<Coor>>>() {
//            @Override
//            public void onSuccess(Response<BaseResponse<ArrayList<Coor>>> response) {
//                if (response.body().code == 1) {
//                    coors = response.body().data;
//                    setfromandtoMarker();
//                }
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//            }
//        });
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
        aMap.setTrafficEnabled(true);// 显示实时交通状况
        aMap.setOnMapLoadedListener(this);
    }

    @Override
    public void onMapLoaded() {

    }


    public void searchRouteResult(int routeType, int mode) {
        if (mStartPoint == null) {
//            ToastUtil.show(mContext, "定位中，稍后再试...");
//            Share.e("定位中，稍后再试...");
            return;
        }
        if (mEndPoint == null) {
//            Share.e("终点未设置");
//            ToastUtil.show(mContext, "终点未设置");
        }
        showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);
        if (routeType == ROUTE_TYPE_DRIVE) {// 驾车路径规划
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, mode, points,
                    null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
//            mRouteSearch.calculateDriveRoute();
        }
    }

    private ProgressDialog progDialog = null;// 搜索时进度条

    private void showProgressDialog() {
        if (progDialog == null) {
            progDialog = new ProgressDialog(this);
        }
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在搜索");
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }


    List<LatLonPoint> points;

    private void setfromandtoMarker(List<CheliangGuiJi.DataBean> coors) {
        points = new ArrayList<>();
        for (CheliangGuiJi.DataBean coor : coors) {
            if (coor.getKemu().equals("起点")) {
                mStartPoint = new LatLonPoint(Double.valueOf(coor.getAchievement()), Double.valueOf(coor.getName()));
                aMap.addMarker(new MarkerOptions()
                        .position(AMapUtil.convertToLatLng(mStartPoint))
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.nav_route_result_start_point)));
            } else if (coor.getKemu().equals("终点")) {
                mEndPoint = new LatLonPoint(Double.valueOf(coor.getAchievement()), Double.valueOf(coor.getName()));
                aMap.addMarker(new MarkerOptions()
                        .position(AMapUtil.convertToLatLng(mEndPoint))
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.nav_route_result_end_point)));
            } else {
                LatLonPoint mPoint = new LatLonPoint(Double.valueOf(coor.getAchievement()), Double.valueOf(coor.getName()));
                points.add(mPoint);
                aMap.addMarker(new MarkerOptions().position(AMapUtil.convertToLatLng(mPoint)).snippet("DefaultMarker"));
            }
        }

        searchRouteResult(ROUTE_TYPE_DRIVE, RouteSearch.DrivingDefault);
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        dissmissProgressDialog();
        aMap.clear();// 清理地图上的所有覆盖物
        for (CheliangGuiJi.DataBean coor : data) {
            LatLonPoint mPoint = new LatLonPoint(Double.valueOf(coor.getAchievement()), Double.valueOf(coor.getName()));
            aMap.addMarker(new MarkerOptions().position(AMapUtil.convertToLatLng(mPoint)).snippet("到达时间:" + coor.getTime()));
        }
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mDriveRouteResult = result;
                    final DrivePath drivePath = mDriveRouteResult.getPaths()
                            .get(0);
                    if (drivePath == null) {
                        return;
                    }
                    DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                            context, aMap, drivePath,
                            mDriveRouteResult.getStartPos(),
                            mDriveRouteResult.getTargetPos(), null);
                    drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
//                    drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();
//                    mBottomLayout.setVisibility(View.VISIBLE);
//                    int dis = (int) drivePath.getDistance();
//                    int dur = (int) drivePath.getDuration();
//                    String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";
//                    mRotueTimeDes.setText(des);
//                    mRouteDetailDes.setVisibility(View.VISIBLE);
//                    int taxiCost = (int) mDriveRouteResult.getTaxiCost();
//                    mRouteDetailDes.setText("打车约" + taxiCost + "元");
//                    mBottomLayout.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            Intent intent = new Intent(mContext,
//                                    DriveRouteDetailActivity.class);
//                            intent.putExtra("drive_path", drivePath);
//                            intent.putExtra("drive_result",
//                                    mDriveRouteResult);
//                            startActivity(intent);
//                        }
//                    });

                } else if (result != null && result.getPaths() == null) {
                    Toast.makeText(context, "对不起没有搜索到相关数据", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(context, "对不起没有搜索到相关数据", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "errorCode>>" + errorCode, Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }
}
